<script setup lang="ts">
import {
  type ColProps,
  FormInstance,
  ValidatedError,
} from "@arco-design/web-vue";
import { useI18n } from "vue-i18n";
import useLoginStroe from "@/stores/modules/useLoginStroe.ts";
import { reactive, ref } from "vue";
import type { LoginPhoneSubmitType } from "@/types/loginType.ts";
import type { FormRule } from "@/types/commonType.ts";
import matchRules from "@/utils/Regexp";

defineProps<{
  labelColProps: ColProps;
  wrapperColProps: ColProps;
}>();

const { t } = useI18n();

const {
  setIsAccountOrPhone,
  phoneGetCode,
  getCountDown,
  getIsCode,
  phoneSubmit,
} = useLoginStroe();

const formRef = ref<FormInstance>();

const formModel = reactive<LoginPhoneSubmitType>({
  phone: "",
  code: "",
});

const rules: FormRule<keyof LoginPhoneSubmitType> = {
  phone: [
    {
      required: true,
      message: "请输入手机号",
    },
    {
      match: matchRules.getRegexp("CNphoneRules"),
      message: "请输入正确的手机号",
    },
  ],
  code: {
    required: true,
    message: "请输入验证码",
  },
};

const handleSubmit = () => {
  formRef.value?.validate(
    (errors: undefined | Record<string, ValidatedError>) => {
      if (errors === undefined) {
        phoneSubmit(formModel);
      }
    }
  );
};

const handleCode = () => {
  formRef.value?.validateField(
    ["phone"],
    (errors: undefined | Record<string, ValidatedError>) => {
      if (errors === undefined) {
        phoneGetCode(formModel.phone);
      }
    }
  );
};
</script>

<template>
  <a-form
    :rules="rules"
    :model="formModel"
    ref="formRef"
    :label-col-props="labelColProps"
    :wrapper-col-props="wrapperColProps"
  >
    <a-form-item
      field="phone"
      validate-trigger="input"
    >
      <a-input
        allow-clear
        v-model="formModel.phone"
        placeholder="请输入手机号"
      ></a-input>
    </a-form-item>
    <a-form-item field="code">
      <a-input
        allow-clear
        v-model="formModel.code"
        placeholder="请输入验证码"
      >
        <template #append>
          <a-button
            v-if="getIsCode()"
            style='user-select: none;'
          >{{ getCountDown() }}</a-button>
          <a-button
            style='user-select: none;'
            v-else
            @click="handleCode"
          >获取验证码</a-button>
        </template>
      </a-input>
    </a-form-item>

    <a-form-item>
      <a-button
        type="primary"
        long
        @click="handleSubmit"
      >登录</a-button>
    </a-form-item>

    <a-form-item>
      <a-button
        type="primary"
        long
        @click="setIsAccountOrPhone(true)"
      >账号密码登录</a-button>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="scss">
:deep(.arco-form-item-message) {
  color: #ff9854 !important;
}

:deep(.arco-btn-primary) {
  background: linear-gradient(to right, #5e8eff, #0c55ff);
  border: none;
}
</style>